<?php 
/**
 * GPS<=>地理位置
 * @Author    紫梦
 * @DateTime  2018-03-01
 * @copyright 响响租车
 * @version   1.0
 */
namespace app\common\controller;
use app\common\request\Curl;
use think\facade\Log;

class Gps
{

    public static function geoCode($lng,$lat)
    {   
        $host = "http://restapi.amap.com";
        $path = "/v3/geocode/regeo";
        $transgps = self::transGps($lng,$lat);
        if($transgps){
      
            $location = $transgps['locations']??'';
            $key = "df2e1065cd36933573cf408a88aaf63e";
            $url = $host . $path . "?" . "key=" . $key . "&location=" . $location . "&batch=false";

            $curl = new Curl; 
            $curl->url($url);

            if ($curl->error()) {
                Log::record('[ 请求错误 ] '.$curl->message(),'error');
                return false;
                
            } else {
                $info = $curl->info();                
                if($info['http_code'] == 200){
                  
                    $arr = json_decode($curl->data(),true);
                    if($arr !== null){
                        return $arr;
                    }else{
                        Log::record('[ 解码失败 ] '.$curl->data(),'error');
                        return false;
                    }         

                }else{
                    Log::record('[ 请求目标 ] '.$curl->data() .$info['http_code'],'error');
                    return false;
                }
            }           
        }

        return false;
    }

    public static function transGps($lng,$lat){
        $host = "http://restapi.amap.com";
        $path = "/v3/assistant/coordinate/convert";
        $key = "df2e1065cd36933573cf408a88aaf63e";
        $locations = "$lng,$lat&coordsys=gps";
        $url = $host . $path . "?" . "key=" . $key . "&locations=" . $locations;

        $curl = new Curl; 
        $curl->url($url);
        
        if ($curl->error()) {
            
            Log::record('[ 请求错误 ] '.$curl->message(),'error');
            return false;
            
        } else {   
            
            $info = $curl->info(); 
            if($info['http_code'] == 200){
                $arr = json_decode($curl->data(),true);
                if($arr !== null){
                    return $arr;
                }else{
                    Log::record('[ 解码失败 ] '.$curl->data(),'error');
                    return false;
                }             
            }else{
                Log::record('[ 请求目标 ] '.$curl->data() .$info['http_code'],'error');
                return false;
            }
        }
    }

}